<?php
// +----------------------------------------------------------------------
// | 阿里云短信
// +----------------------------------------------------------------------

namespace helper\ali;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\QuerySendDetailsRequest;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendBatchSmsRequest;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use Darabonba\OpenApi\Models\Config;
use helper\facade\ISms;

class Sms implements ISms
{
    private array $config;

    public function __construct($config)
    {
        $this->config = [
            'accessKeyId'     => $config['accessKeyId'],
            'accessKeySecret' => $config['accessKeySecret'],
            'signName'        => $config['signName'],
            'templateCode'    => $config['templateCode'],
        ];
    }

    /**
     * 使用AK&SK初始化账号Client
     * @return Dysmsapi
     */
    public function createClient()
    {
        $config = new Config([
            // 您的AccessKey ID
            "accessKeyId"     => $this->config['accessKeyId'],
            // 您的AccessKey Secret
            "accessKeySecret" => $this->config['accessKeySecret']
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /**
     * 短信发送
     * @param $mobile string
     * @param $templateCode string
     * @param $templateParam array
     * @return array
     */
    public function sendSms(string $mobile, string $templateCode, array $templateParam): array
    {
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers"  => $mobile,
            "signName"      => $this->config['signName'],
            "templateCode"  => $this->config[$templateCode],
            "templateParam" => $templateParam ? json_encode($templateParam) : '{}'
        ]);
        $response       = self::createClient()->sendSms($sendSmsRequest);
        if ($response->body->code == 'OK') {
            return ['code' => 0, 'message' => $response->body->message];
        }
        return ['code' => 1, 'message' => $response->body->message];
    }

    /**
     * 批量发送短信
     */
    public function sendBatchSms()
    {
        $client              = $this->createClient();
        $sendBatchSmsRequest = new SendBatchSmsRequest([]);
        $client->sendBatchSms($sendBatchSmsRequest);
    }

    /**
     * 查看短信发送记录和发送状态
     */
    public function QuerySendDetails()
    {
        $client                  = $this->createClient();
        $querySendDetailsRequest = new QuerySendDetailsRequest([]);
        $client->querySendDetails($querySendDetailsRequest);
    }
}
